

const net = require('net');
const { error } = require('./error');

const retryTimeout = 3000;   //连接超时重新连接时间
let retriedTimes = 0;      //重新尝试的次数
const maxRetries = 10;       //最多尝试的次数

class AvenirSQL {

    constructor() {
        this.ip = null;
        this.user = null;
        this.password = null;
        this.sign = null;
        this.database = null;
        this.conn = null;
        this.port = null;
    }

    //初始化 告诉数据库要用何种连接信息
    init(data) {
        this.ip = data.ip;
        this.user = data.user;
        this.password = data.password;
        this.database = data.database;
        this.port = data.port;
    }

    //连接获得签名
    async connect() {
        if ((!this.ip) || (!this.user) || (!this.password) || (!this.port)) {
            throw (error.LACK_OF_PARAMS);
        }
        let sendJson = {
            user: this.user,
            password: this.password,
            type: "login",
        }
        let res = await this.send(sendJson,'login');
        return res;
        
    }
    //发送数据
    async send(json,type) {
        let promise = new Promise((resolve, reject) => {
            let client = new net.Socket();  //后期改缓存连接
            client.connect({
                host: this.ip,
                port: this.port
            })

            //客户端与服务器建立连接触发
            client.on('connect', () => {
                client.write(JSON.stringify(json));
            });

            //客户端接收数据触发
            client.on('data', (data) => {
                client.end();
                let res = JSON.parse(data);
                if(res.code === 0 && type === 'login') {
                    this.sign = res.data;
                }
                resolve(JSON.parse(data));
            });

            client.on('error', (error) => {
                reject(error);
            })
        })
        return promise;
    }

    async dbop(sql,sign) {
        let sendJson = {
            sign:sign || this.sign,
            type : 'sql',
            data:sql,
        }
        return await this.send(sendJson);
    }
}

module.exports = AvenirSQL;